﻿using System;
using System.Reflection;

namespace INNOVACALL.Framework.Common.MVCHelpers.Localization
{
    /// <summary>
    /// Utilitaires pour les classes helpers de localisation
    /// </summary>
    public class CommonLocalization
    {
        /// <summary>
        /// Permet de scruter une ressource en vue de l'utiliser dans DisplayNameLocalizedAttribute
        /// Exemple d'utilisation pour un fichier de ressource qui s'appellerait Titles.resx
        /// qui contiendrait 2 chaines : CreationDateDisplayName et CreationDateDescription
        /// [Common.DisplayNameLocalized(typeof(Resources.Titles), "CreationDateDisplayName"),
        /// Common.DescriptionLocalized(typeof(Resources.Titles), "CreationDateDescription")]
        /// public DateTime CreationDate
        /// {
        ///   get;
        ///   set;
        /// }
        /// </summary>
        /// <param name="resourceManagerProvider"></param>
        /// <param name="resourceKey"></param>
        /// <returns></returns>
        public static string LookupResource(Type resourceManagerProvider, string resourceKey)
        {
            //Très important, (BindingFlags.Static | BindingFlags.Public) si la ressource est publique, il faut utiliser BindingFlags.Public sinon BindingFlags.NonPublic
            foreach (PropertyInfo staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.Public))
            {
                if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager))
                {
                    System.Resources.ResourceManager resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null);
                    return resourceManager.GetString(resourceKey);
                }
            }

            return resourceKey;
        }
    }
}
